import { defineStore } from 'pinia';

export const useThemeStore = defineStore('theme', () => {
  // 主题状态
  const isDark = ref(false);
  const isInitialized = ref(false);
  const themeMode = ref<'light' | 'dark' | 'auto'>('light');

  // 应用主题到DOM，用于Tailwind暗色模式
  const applyThemeToDOM = () => {
    if (import.meta.client) {
      // 为HTML元素添加或移除dark类，用于Tailwind
      if (isDark.value) {
        document.documentElement.classList.add('dark');
      }
      else {
        document.documentElement.classList.remove('dark');
      }
    }
  };

  // 设置主题模式
  const setThemeMode = (mode: 'light' | 'dark' | 'auto') => {
    themeMode.value = mode;

    if (mode === 'auto') {
      // 自动模式下，根据系统偏好设置
      if (import.meta.client) {
        isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
      }
      else {
        // 服务端默认使用light
        isDark.value = false;
      }
    }
    else {
      isDark.value = mode === 'dark';
    }

    if (import.meta.client) {
      localStorage.setItem('theme-mode', mode);
      applyThemeToDOM();
    }
  };

  // 初始化主题
  const initTheme = () => {
    if (import.meta.client && !isInitialized.value) {
      // 从 localStorage 读取保存的主题设置
      const savedThemeMode = localStorage.getItem('theme-mode') as 'light' | 'dark' | 'auto' | null;

      if (savedThemeMode) {
        themeMode.value = savedThemeMode;

        if (savedThemeMode === 'auto') {
          // 自动模式下，根据系统偏好设置
          isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
        }
        else {
          isDark.value = savedThemeMode === 'dark';
        }
      }
      else {
        // 如果没有保存的设置，使用环境变量的默认值
        const { DEFAULT_THEME_MODEL } = useRuntimeConfig();
        const defaultMode = DEFAULT_THEME_MODEL?.toLowerCase() as 'light' | 'dark' | 'auto' || 'light';
        themeMode.value = defaultMode;

        if (defaultMode === 'auto') {
          // 自动模式下，根据系统偏好设置
          isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
        }
        else {
          isDark.value = defaultMode === 'dark';
        }
      }
      isInitialized.value = true;
    }
    else if (import.meta.server) {
      // 服务端渲染时，使用环境变量的默认值
      const { DEFAULT_THEME_MODEL } = useRuntimeConfig();
      const defaultMode = DEFAULT_THEME_MODEL?.toLowerCase() as 'light' | 'dark' | 'auto' || 'light';
      themeMode.value = defaultMode;

      // 服务端无法检测系统偏好，如果是auto模式，默认使用light
      isDark.value = defaultMode === 'dark';
      isInitialized.value = true;
    }

    // 应用主题到HTML元素，用于Tailwind暗色模式
    applyThemeToDOM();
  };

  // 切换主题
  const toggleTheme = () => {
    // 如果当前是自动模式，切换为明确的模式
    if (themeMode.value === 'auto') {
      setThemeMode(isDark.value ? 'dark' : 'light');
    }
    else {
      // 否则在明暗模式之间切换
      setThemeMode(isDark.value ? 'light' : 'dark');
    }
  };

  // 监听系统主题变化
  const watchSystemTheme = () => {
    if (import.meta.client) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
      mediaQuery.addEventListener('change', (e) => {
        // 只有在自动模式下才跟随系统
        if (themeMode.value === 'auto') {
          isDark.value = e.matches;
          applyThemeToDOM();
        }
      });
    }
  };

  return {
    isDark: readonly(isDark),
    isInitialized: readonly(isInitialized),
    themeMode: readonly(themeMode),
    initTheme,
    toggleTheme,
    setThemeMode,
    watchSystemTheme,
    applyThemeToDOM,
  };
});
